import { Inject, Injectable } from '@nestjs/common';
import { CreateEmploymentDto } from './dto/create-employment.dto';
import { UpdateEmploymentDto } from './dto/update-employment.dto';
import { Like, Repository } from 'typeorm';
import { Employment } from './entities/employment.entity';
import { SearchPagesDto } from './dto/search-pages.dto';

@Injectable()
export class EmploymentService {
  constructor(
    @Inject('EMPLOYMENT_REPOSITORY')
    private employmentRepository: Repository<Employment>,
  ) {}
  async create(createEmploymentDto: CreateEmploymentDto) {
    try {
      const Employment = this.employmentRepository.create(createEmploymentDto);
      return await this.employmentRepository.save(Employment);
    } catch (error) {
      console.log(error);
      throw new Error(error);
    }
  }

  findAll() {
    return `This action returns all employment`;
  }

  async findAllPage(pages: SearchPagesDto) {
    const { page = 1, limit = 10, leibie, biaoti } = pages;
    const skip = (page - 1) * limit;

    // 构建查询条件
    const where: any = {};

    if (leibie) {
      where.leibie = Like(`%${leibie}%`); // 模糊查询
    }

    if (biaoti) {
      where.biaoti = Like(`%${biaoti}%`); // 模糊查询
    }

    const [list, total] = await this.employmentRepository.findAndCount({
      where,
      skip,
      take: limit,
      order: { createTime: 'DESC' },
    });

    return {
      list,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  findOne(id: number) {
    return this.employmentRepository.findOne({
      where: {
        id: id,
      },
    });
  }

  update(id: number, updateEmploymentDto: UpdateEmploymentDto) {
    return this.employmentRepository.update(id, updateEmploymentDto);
  }

  remove(id: number) {
    return this.employmentRepository.delete(id);
  }
  // 可选：添加批量删除方法
  async batchRemove(ids: number[]) {
    console.log(ids);

    const result = await this.employmentRepository
      .createQueryBuilder()
      .delete()
      .whereInIds(ids)
      .execute();

    return { affected: result.affected };
  }
}
